package com.wontube.web.i18n;

import java.util.Locale;
import java.util.ResourceBundle;


/**
 * i18n issue
 * i18n结构: (相对于classpath下)
 * i18n/name_en_US.properties
 * i18n/name_zh_CN.properties
 * @author tanggf(2012-4-9)
 *
 */
public class I18nManager {		
	//相对于classpath
	public static String bundleRoot = "i18n";
	public static Locale defaultLocale = Locale.US;
	/** bundle缓存时间 */
	private static long time2live= 5 * 60 * 1000L;
		
	/**
	 * 从默认的locale文件夹下的bundle文件读取
	 * @param key
	 * @param bundleName
	 * @return
	 */
	public static String getMessage(String key, String bundleName){		
		return getMessage(key, bundleName, defaultLocale);
	}

	/**
	 * 在指定locale文件夹下的bundle文件中读取
	 * @param key
	 * @param bundleName
	 * @param locale
	 * @return
	 */
	public static String getMessage(String key, String bundleName, Locale locale){
		if(key == null || bundleName == null){
			return null;
		}
		
		if(locale == null){
			locale = defaultLocale;
		}	
		
		String baseName = joinBaseName(bundleName, locale);			
		try {
			ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, new ReloadResourceControl());	
			return bundle.getString(key);
		} catch (Exception e) {
			return null;
		}			
	}
	
	private final static class ReloadResourceControl extends ResourceBundle.Control {	
		@Override
		public long getTimeToLive(String baseName, Locale locale) {
			return I18nManager.time2live;
		}	
	}	

	private static String joinBaseName(String bundleName, Locale locale) {				
		return bundleRoot + "." + bundleName;		
	}
}
